<?php

namespace Admin\Controller;

/**
 * 试卷详情控制器
 *
 * @author zhiyuan
 *        
 */
define ( 'DOCX_TEMP_PATH', 'DownLoads/PaperDocuments/' );
define ( 'PAPER_DOCUMENTS_PATH', 'DownLoads/PaperDocuments/' );
class PaperDetailsController extends AdminController {
	public function index() {
		$paper_id = I ( 'paper' );
		$map = array (
				'owner' => array (
						'eq',
						UID 
				),
				'paper' => array (
						'eq',
						$paper_id 
				) 
		);
		$list = $this->lists ( 'PaperDetails', $map, array (
				'set',
				'set' => 'asc' 
		) );
		$this->assign ( 'paperid', $paper_id );
		$this->assign ( 'list', $list );
		$this->meta_title = '试卷详情';
		$this->display ();
	}
	
	/**
	 * 生成试卷文档
	 *
	 * @return string
	 */
	public function paperdocx(array $paper, array $paperdetail) {
		// 文档初始配置
		$DocxProperties = C ( 'APP_WORDDOCUMENT_PROPERTIES' );
		$PaperHeaderPath = C ( 'PAPER_HEADER_PATH' );
		$PaperHeaderStyle = C ( 'APP_PAPER_HEADER_STYLE' );
		$PaperSectionStyle = C ( 'APP_PAPER_SECTION_STYLE' );
		$PaperFooterPage = '第{PAGE}页（共{NUMPAGES}页）';
		$IndentSpace2 = str_repeat ( ' ', 2 );
		$IndentSpace5 = str_repeat ( ' ', 5 );
		$MasterTitleFontStyle = array (
				'name' => '宋体',
				'bold' => true,
				'size' => 18 
		);
		$SecondTitleFontStyle = array (
				'name' => '宋体',
				'size' => 14 
		);
		$TypeFontStyle = array (
				'name' => '宋体',
				'bold' => true,
				'size' => 10 
		);
		$TextFontStyle = array (
				'name' => '宋体',
				'size' => 10 
		);
		$PicTabFontStyle = array (
				'name' => '宋体',
				'size' => 9 
		);
		$FooterFontStyle = array (
				'name' => '宋体',
				'size' => 9 
		);
		$AlignLeft = array (
				'align' => 'left' 
		);
		$AlignCenter = array (
				'align' => 'center' 
		);
		$AlignRight = array (
				'align' => 'right' 
		);
		
		// 设置试卷主标题或文档名称、副标题、题型、题型数量、题型分值、题型信息
		$MasterTitle = $paper ['mastertitle'] . '（' . num2letter ( $paperdetail ['set'] ) . '卷）';
		$SecondTitle = '（' . $paper ['secondtitle'] . '    总分：' . $paper ['score'] . '分）';
		$QuestionTypes = str2arr ( $paper ['types'], ',' );
		$TypesCount = str2arr ( $paper ['types_count'], ',' );
		$TypesScore = str2arr ( $paper ['types_score'], ',' );
		$TypesInfo = str2arr ( $paper ['types_info'], '`' );
		
		// 获取试题ID及对应题型数组
		$Types = str2arr ( $paperdetail ['types'], ',' );
		$QustionsIds = str2arr ( $paperdetail ['questions'], ',' );
		
		// 引入PHPWord
		require_once 'ThinkPHP/Library/PHPWord/PHPWord.php';
		// 新建PHPWord类
		$PaperWord = new \PHPWord ();
		// 设置属性
		$properties = $PaperWord->getProperties ();
		$properties->setCreator ( $DocxProperties ['creator'] );
		$properties->setCompany ( $DocxProperties ['company'] );
		$properties->setLastModifiedBy ( $DocxProperties ['lastmodifiedby'] );
		// 页面设置
		$section = $PaperWord->createSection ( $PaperSectionStyle );
		// 试卷头设置
		$header = $section->createHeader ();
		$header->addWatermark ( $PaperHeaderPath, $PaperHeaderStyle );
		// 页脚页码设置
		$footer = $section->createFooter ();
		$footer->addPreserveText ( $PaperFooterPage, $FooterFontStyle, $AlignRight );
		// 写入内容
		$section->addText ( $MasterTitle, $MasterTitleFontStyle, $AlignCenter );
		$section->addText ( $SecondTitle, $SecondTitleFontStyle, $AlignCenter );
		$section->addTextBreak ( 1 );
		
		foreach ( $QuestionTypes as $key => $value ) {
			// 写入题型文本
			$TypeText = num2ch ( $key + 1 ) . '、' . get_questiontype_name ( $value ) . '（' . $TypesInfo [$key] . '  共' . $TypesCount [$key] . '小题，' . $TypesScore [$key] . '分）';
			$section->addText ( $TypeText, $TypeFontStyle, $AlignLeft );
			// 写入试题
			$sn = 0;
			foreach ( $Types as $key1 => $value1 ) {
				if ($value === $value1) {
					$Qustion = D ( 'Questions' )->field ( true )->find ( $QustionsIds [$key1] );
					// 写入题干
					$sn ++;
					$TitleArr = str2arr ( $Qustion ['title'], "\r\n" );
					foreach ( $TitleArr as $key2 => $value2 ) {
						if ($key2 == 0) {
							$section->addText ( $IndentSpace2 . $sn . '. ' . $value2, $TextFontStyle, $AlignLeft );
						} else {
							$section->addText ( $IndentSpace5 . $value2, $TextFontStyle, $AlignLeft );
						}
					}
					$section->addTextBreak ( $Qustion ['answer_rows'] );
					
					// 写入附件
					$attachmentsmap = array (
							'question' => array (
									'eq',
									$Qustion ['id'] 
							) 
					);
					$ordermap = array (
							'order' => 'asc',
							'id' => 'asc' 
					);
					$QuestionAttachments = D ( 'QuestionAttachments' )->where ( $attachmentsmap )->order ( $ordermap )->field ( true )->select ();
					foreach ( $QuestionAttachments as $key3 => $value3 ) {
						if ($QuestionAttachments [$key3] ['type'] == 0) {
							$section->addImage ( $QuestionAttachments [$key3] ['image'], $AlignLeft );
							$section->addText ( $IndentSpace5 . $QuestionAttachments [$key3] ['text'], $PicTabFontStyle );
						} else {
							$AttachmentsArr = str2arr ( $QuestionAttachments [$key3] ['text'], "\r\n" );
							foreach ( $AttachmentsArr as $key4 => $value4 ) {
								$section->addText ( $IndentSpace5 . $value4 );
							}
						}
						$section->addTextBreak ( $QuestionAttachments [$key3] ['answer_rows'] );
					}
				}
			}
			$section->addTextBreak ( 1 );
		}
		
		// 存储文件
		$DocxPath = DOCX_TEMP_PATH . UID . '/';
		if (! file_exists ( $DocxPath )) {
			@mkdir ( $DocxPath );
		}
		$PaperDocx = iconv ( 'utf-8', 'GBK', $MasterTitle . '.docx' );
		$objWriter = \PHPWord_IOFactory::createWriter ( $PaperWord, 'Word2007' );
		$objWriter->save ( $DocxPath . $PaperDocx );
		if (file_exists ( $DocxPath . $PaperDocx )) {
			return $PaperDocx;
		} else {
			return null;
		}
	}
	public function answerdocx(array $paper, array $paperdetail) {
		// 文档初始配置
		$DocxProperties = C ( 'APP_WORDDOCUMENT_PROPERTIES' );
		$AnswerSectionStyle = C ( 'APP_ANSWER_SECTION_STYLE' );
		$PaperFooterPage = '第{PAGE}页（共{NUMPAGES}页）';
		$IndentSpace2 = str_repeat ( ' ', 2 );
		$IndentSpace5 = str_repeat ( ' ', 5 );
		$MasterTitleFontStyle = array (
				'name' => '宋体',
				'bold' => true,
				'size' => 14 
		);
		$TypeFontStyle = array (
				'name' => '宋体',
				'bold' => true,
				'size' => 10 
		);
		$TextFontStyle = array (
				'name' => '宋体',
				'size' => 10 
		);
		$PicTabFontStyle = array (
				'name' => '宋体',
				'size' => 9 
		);
		$FooterFontStyle = array (
				'name' => '宋体',
				'size' => 9 
		);
		$AlignLeft = array (
				'align' => 'left' 
		);
		$AlignCenter = array (
				'align' => 'center' 
		);
		$AlignRight = array (
				'align' => 'right' 
		);
		
		// 设置试卷主标题或文档名称、副标题、题型、题型数量、题型分值、题型信息
		$MasterTitle = $paper ['mastertitle'] . '（' . num2letter ( $paperdetail ['set'] ) . '卷）答案';
		$QuestionTypes = str2arr ( $paper ['types'], ',' );
		
		// 获取试题ID及对应题型数组
		$Types = str2arr ( $paperdetail ['types'], ',' );
		$QustionsIds = str2arr ( $paperdetail ['questions'], ',' );
		
		// 引入PHPWord
		require_once 'ThinkPHP/Library/PHPWord/PHPWord.php';
		// 新建PHPWord类
		$AnswerWord = new \PHPWord ();
		// 设置属性
		$properties = $AnswerWord->getProperties ();
		$properties->setCreator ( $DocxProperties ['creator'] );
		$properties->setCompany ( $DocxProperties ['company'] );
		$properties->setLastModifiedBy ( $DocxProperties ['lastmodifiedby'] );
		// 页面设置
		$section = $AnswerWord->createSection ( $AnswerSectionStyle );
		// 页脚页码设置
		$footer = $section->createFooter ();
		$footer->addPreserveText ( $PaperFooterPage, $FooterFontStyle, $AlignRight );
		// 写入内容
		$section->addText ( $MasterTitle, $MasterTitleFontStyle, $AlignCenter );
		$section->addTextBreak ( 1 );
		
		foreach ( $QuestionTypes as $key => $value ) {
			// 写入题型文本
			$TypeText = num2ch ( $key + 1 ) . '、' . get_questiontype_name ( $value );
			$section->addText ( $TypeText, $TypeFontStyle, $AlignLeft );
			// 写入试题
			$sn = 0;
			foreach ( $Types as $key1 => $value1 ) {
				if ($value === $value1) {
					// 写入题号
					$sn ++;
					$section->addText ( $IndentSpace2 . $sn . '. 答案', $TextFontStyle, $AlignLeft );
					// 写入答案
					$answersmap = array (
							'question' => array (
									'eq',
									$QustionsIds [$key1] 
							) 
					);
					$ordermap = array (
							'order' => 'asc',
							'id' => 'asc' 
					);
					$QuestionAnswers = D ( 'QuestionAnswers' )->where ( $answersmap )->order ( $ordermap )->field ( true )->select ();
					foreach ( $QuestionAnswers as $key2 => $value2 ) {
						if ($QuestionAnswers [$key2] ['type'] == 0) {
							$section->addImage ( $QuestionAnswers [$key2] ['image'], $AlignLeft );
							$section->addText ( $IndentSpace5 . $QuestionAnswers [$key2] ['text'], $PicTabFontStyle );
						} else {
							$AnswersArr = str2arr ( $QuestionAnswers [$key2] ['text'], "\r\n" );
							foreach ( $AnswersArr as $key3 => $value3 ) {
								$section->addText ( $IndentSpace5 . $value3 );
							}
						}
					}
				}
			}
			$section->addTextBreak ( 1 );
		}
		
		// 存储文件
		$DocxPath = DOCX_TEMP_PATH . UID . '/';
		if (! file_exists ( $DocxPath )) {
			@mkdir ( $DocxPath );
		}
		$AnswerDocx = iconv ( 'utf-8', 'GBK', $MasterTitle . '.docx' );
		$objWriter = \PHPWord_IOFactory::createWriter ( $AnswerWord, 'Word2007' );
		$objWriter->save ( $DocxPath . $AnswerDocx );
		if (file_exists ( $DocxPath . $AnswerDocx )) {
			return $AnswerDocx;
		} else {
			return null;
		}
	}
	public function builddocument() {
		// 生成试卷压缩包
		$paper_id = I ( 'paper' );
		$paper = D ( 'Papers' )->field ( true )->find ( $paper_id );
		if ($paper ['owner'] === UID && $paper ['status'] === '0') {
			$map = array (
					'owner' => array (
							'eq',
							UID 
					),
					'paper' => array (
							'eq',
							$paper_id 
					) 
			);
			$paperdetails = D ( 'PaperDetails' )->where ( $map )->field ( true )->order ( array (
					'set',
					'set' => 'asc' 
			) )->select ();
			
			// 定义临时文档数组
			$DocxArr = array ();
			// 生成试卷压缩包
			$ZipFile = md5 ( UID . NOW_TIME ) . '.zip';
			// 创建 ZIP
			$objZip = new \ZipArchive ();
			// 打开 ZIP 文档
			$ZipFilePath = PAPER_DOCUMENTS_PATH . UID . '/';
			if ($objZip->open ( $ZipFilePath . $ZipFile, \ZIPARCHIVE::OVERWRITE ) !== true) {
				if ($objZip->open ( $ZipFilePath . $ZipFile, \ZIPARCHIVE::CREATE ) !== true) {
					throw new Exception ( "Could not open " . $ZipFile . " for writing." );
				}
			}
			
			foreach ( $paperdetails as $key => $value ) {
				$paperdocx = $this->paperdocx ( $paper, $paperdetails [$key] );
				$answerdocx = $this->answerdocx ( $paper, $paperdetails [$key] );
				if ($paperdocx != null && $answerdocx != null) {
					$objZip->addFile ( $ZipFilePath . $paperdocx, $paperdocx );
					$objZip->addFile ( $ZipFilePath . $answerdocx, $answerdocx );
					$DocxArr [] = $ZipFilePath . $paperdocx;
					$DocxArr [] = $ZipFilePath . $answerdocx;
				} else {
					$this->error ( '试卷生成失败' );
				}
			}
			$objZip->close ();
			// 删除临时文档
			foreach ( $DocxArr as $key => $value ) {
				@unlink ( $value );
			}
			if (file_exists ( $ZipFilePath . $ZipFile )) {
				// 写入下载地址
				$PaperDocuments = D ( 'PaperDocuments' );
				$data = $PaperDocuments->create ();
				$data ['title'] = $paper ['name'];
				$data ['link_url'] = $ZipFilePath . $ZipFile;
				$data ['user'] = UID;
				$data ['create_time'] = NOW_TIME;
				$data ['update_time'] = NOW_TIME;
				$data ['status'] = 1;
				if ($PaperDocuments->add ( $data )) {
					$this->success ( '生成试卷成功', U ( 'PaperDocuments/index' ) );
				} else {
					$this->error ( '生成试卷失败' );
				}
			} else {
				$this->error ( '试卷生成失败' );
			}
		} else {
			$this->error ( '对不起，您不具有访问权限!' );
		}
	}
}
?>